﻿var dx = 'tbody tr td .dxeEditArea';
var _freeDays = parseInt($('#ASPxFreeDays').find(dx).val()),
    _maxDays = parseInt($("#ASPxMaxDays").find(dx).val()),
    _minPriceWithDiscount = parseInt($("#ASPxMinPriceWithDiscount").find(dx).val()),
    _oneDayPlacementPrice = parseInt($("#ASPxOneDayPlacementPrice").find(dx).val()),
    
    _oneLiftPrice = parseInt($("#ASPxOneLiftPrice").find(dx).val()),
    _maxLifts = parseInt($("#ASPxMaxRaiseCount").find(dx).val()),
    _maxDiscountTopper = parseInt($('#ASPxMaxDiscountTopper').find(dx).val()),
    liftMessageCount = $('#liftmessagecount'),
    priceAfterDiscount2 = $('#priceAfterDiscount2'),
    priceBeforeDiscount2 = $('#priceBeforeDiscount2'),
    discountLifts = $('#discountLifts'),
    discountTerm = $('#discountTerm'),
    liftMessageFrequncy = $('#liftmessagefrequncy'),
    liftMessageTime = $('#liftmessagetime'),
    liftMessagePrice = $('#liftmessageprice');

    _minPriceTerm = parseInt($("#ASPxMinPriceWithoutDiscount").find(dx).val()),
    _maxDiscountTerm = parseInt($('#ASPxMaxDiscount').find(dx).val()),
    _minDiscountTerm = parseInt($('#ASPxMinDiscount').text()),    
    dateSlider = $('#date-slider'),
    priceSlider = $('#price-slider'),
    liftMessageSlider = $('#lift-message-freq-slider'),
    liftMessageTimeSlider = $('#lift-message-time-slider'),
    liftMessageCountSlider = $('#lift-message-count-slider'),
    liftMessagePriceSlider = $('#lift-message-price-slider'),
    discountTerm = $('#discountTerm'),
    discountOneDay = parseInt((_maxDiscountTerm - _minDiscountTerm) / _maxDays);
    dateFrom = $('#datefrom tbody tr td .dxeEditArea'),
    dateTo = $('#dateto tbody tr td .dxeEditArea'),

txtFreeDays = $('#ASPxFreeDays');
    dateFormat = $('#dateFormate').val();
    
txtDatefrom = $("#ASPxDatefrom  tbody tr td .dxeEditArea"),
txtDateTo = $("#ASPxDateTo  tbody tr td .dxeEditArea"),

dateMin = dateFromString(txtDatefrom.val()),
_dayOfYearMin = getDayOfYear(dateMin),

dateMax = dateFromString(txtDateTo.val()),
_dayOfYearMax = _dayOfYearMin + getDateRange(dateMin, dateMax),

daysRange = $('#daysRange'),
minDaysRange = parseInt(daysRange.text()),
priceAfterDiscount = $('#priceAfterDiscount'),
priceBeforeDiscount = $('#priceBeforeDiscount');

// -------date slider------
dateSlider.slider({ values: [10, 25] });
dateSlider.slider("option", "min", _dayOfYearMin);
dateSlider.slider("option", "max", _dayOfYearMax);

//--------price slider-----
//priceSlider.slider({ values: [_minPriceTerm, _oneDayPlacementPrice * _maxDays] });
priceSlider.slider({ values: [_minPriceTerm, _minPriceTerm + 100] });
priceSlider.slider("option", "min", 0);
priceSlider.slider("option", "max", 1000);


$(document).ready(function () {
    dateFromChange();
});


//----------------EVENTS-----------------------------
function CalcAndSetDateTerm(s, _dateFrom, _dateTo, minDate, maxDate, minRange, minDayOfYear) {

    if (s!=null && s == "datefrom") {
        var maxDateFrom = new Date(_dateTo);
        maxDateFrom = maxDateFrom.addDays((-1) * minRange);

        if (_dateFrom < minDate) {
            _dateFrom = minDate;
        }
        if (_dateFrom > maxDateFrom) {
            _dateFrom = maxDateFrom;
        }
    }

    if (s != null && s == "dateto") {
        var minDateTo = new Date(_dateFrom);
        minDateTo = minDateTo.addDays(minRange);

        if (_dateTo > maxDate) {
            _dateTo = maxDate;
        }
        if (_dateTo < minDateTo) {
            _dateTo = minDateTo;
        }
    }

    var range = getDateRange(_dateFrom, _dateTo);

    aspxGetControlCollection().Get('datefrom').SetDate(new Date(_dateFrom));
    aspxGetControlCollection().Get('dateto').SetDate(new Date(_dateTo));
    daysRange.text(range);
    
    dateSlider.slider("option", "values", [minDayOfYear + getDateRange(minDate, _dateFrom), minDayOfYear + getDateRange(minDate, _dateTo)]);
}


function dateFromChange(s, e) {
    var _dateFrom = dateFromString(dateFrom.val());
    var _dateTo = dateFromString(dateTo.val());

    CalcAndSetDateTerm(s!=null ? s.name : "", _dateFrom, _dateTo, dateMin, dateMax, minDaysRange, _dayOfYearMin);


    _dateFrom = dateFromString(dateFrom.val());
    _dateTo = dateFromString(dateTo.val());

    CalcAndSetPriceTerm(_dateFrom, _dateTo, getDateRange(_dateFrom, _dateTo), _oneDayPlacementPrice);

    
    //var dr = range + _freeDays;
    //liftMessageSlider.slider("option", "max", dr);
    //liftMessageCount.text(dr);
    //priceSlider2.slider("option", "max", dr);
};

function setDatePickers(values) {

    var x = new Date(dateMin);
    var y = new Date(dateMin);

    var newdateFrom = new Date(x.setDate(x.getDate() + (values[0] - _dayOfYearMin)));
    var newdateTo = new Date(y.setDate(y.getDate() + (values[1] - _dayOfYearMin)));

    CalcAndSetDateTerm(newdateFrom.getDate() != dateFromString(dateFrom.val()).getDate() ?
        "datefrom" : newdateTo.getDate() != dateFromString(dateTo.val()).getDate() ? "dateto" : "", newdateFrom, newdateTo, dateMin, dateMax, minDaysRange, _dayOfYearMin);

}

//1.1
dateSlider.slider({
    slide: function (event, ui) {
        var values = ui.values;

        var _discountTerm = discountTerm.text();
        
        if (values[1] - values[0] < minDaysRange) {
            return false;
        }
        
        setDatePickers(values);

       var _dateFrom = dateFromString(dateFrom.val());
        var _dateTo = dateFromString(dateTo.val());

        CalcAndSetPriceTerm(_dateFrom, _dateTo, getDateRange(_dateFrom, _dateTo), _oneDayPlacementPrice);

        //var dr = getDateRange(_dateFrom, _dateTo) + _freeDays;
        //discountTerm.text(parseInt(((dr - _freeDays) * _maxDiscountTerm) / (_maxDays - _freeDays)).toString());
        //liftMessageSlider.slider("option", "max", dr);
        //liftMessageCountSlider.slider("option", "max", dr);
        //liftMessageCountSlider.slider("option", "value", dr);
        //liftMessageCount.text(dr);
        //calcPriceForLifts(null, liftMessageSlider.slider("option", "value"));
        //priceSlider2.slider("option", "max", dr);
    }
});

//1.2
priceSlider.slider({
    disabled: true,
    slide: function (event, ui) {
        //return false;
    }
});

//2.1
liftMessageSlider.slider({
    range: "min",
    value: 1,
    min: 1,
    max: _maxDays,
    slide: function (event, ui) {
        //liftMessageFrequncy.html(ui.value);
        //calcPriceForLifts(null, ui.value);
        //discountLifts.text(Math.ceil((_maxDiscountTopper * (liftMessageCountSlider.slider("option", "value") + 1) / parseInt(getDateRange(dateFrom.val(), dateFrom.val())))));
    }
});

//2.2
liftMessageTimeSlider.slider({
    range: "min",
    value: 20,
    min: 1,
    max: 96,
    slide: function (event, ui) {
        //var allMinutes = ui.value * 15,
        //    hours = Math.floor(allMinutes / 60),
        //    minutes = allMinutes - hours * 60;
        //liftMessageTime.html(hours + '.' + minutes);
    }
});

//2.3
liftMessageCountSlider.slider({
    range: "min",
    //value: _maxLifts / 2,
    value: 500 / 2,
    min: 1,
    //max: _maxLifts / 2,
    max: 500 / 2,
    slide: function (event, ui) {
        //calcPriceForLifts(ui.value);
        //liftMessageCount.html(ui.value);

        //var dr = getDateRange() + _freeDays;
        //var tmpVal = Math.floor(dr / ui.value);
        //if (tmpVal < 1) {
        //    tmpVal = 1;
        //}
        //liftMessageSlider.slider("option", "value", tmpVal);
        //liftMessageFrequncy.text(tmpVal);
        //discountLifts.text(Math.ceil((_maxDiscountTopper * (liftMessageCountSlider.slider("option", "value")) / parseInt(getDateRange(dateFrom.val(), dateFrom.val())))));
    }
});

//2.4
liftMessagePriceSlider.slider({
    range: "min",
    value: 45,
    min: 1,
    max: 50,
    slide: function (event, ui) {
        //liftMessagePrice.html(ui.value / 10);
    }
});



//insert prices to 1.2 and moving slider
function CalcAndSetPriceTerm(dateFrom, dateTo, range, oneDayPlacementPrice) {
    var p = price(dateFrom, dateTo, oneDayPlacementPrice);
    priceBeforeDiscount.text(p);

    discountOneDay = parseFloat((_maxDiscountTerm - _minDiscountTerm) / _maxDays);
    var _discountTerm =parseFloat(discountOneDay * range).toFixed(2);
    discountTerm.text(_discountTerm);

    var pad = parseFloat(p * (1 - parseInt(_discountTerm)/100)).toFixed(2);
    priceAfterDiscount.text(pad);
    
    priceSlider.slider("option", "values", [pad,p]);
}

//returns price for chosen period
function price(dateFrom, dateTo, oneDayPlacementPrice) {
    var daysCount = getDateRange(dateFrom, dateTo);
    var price = parseFloat(daysCount * oneDayPlacementPrice).toFixed(2);
    return price;
}

function dateFromString(str) {
    var date = parseString(str, dateFormat);
    return date;
}

function dateFromDay(year, day) {
    var date = new Date(year, 0); // initialize a date in `year-01-01`
    return new Date(date.setDate(day)); // add the number of days
}

Date.prototype.addDays = function (days) {
    this.setDate(this.getDate() + days);
    return this;
};

//returns pay days (count of days from start date to end date minus free days)
function getDateRange(dateFrom, dateTo) {
    var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
    return Math.round(Math.abs((dateFrom.getTime() - dateTo.getTime()) / (oneDay)));
}

function getDayOfYear(date) {
    var onejan = new Date(date.getFullYear(), 0, 1);
    return Math.ceil((date - onejan) / 86400000);
}

function parseString(val, format) {
    // If no format is specified, try a few common formats
    if (typeof(format) == "undefined" || format == null || format == "") {
        var generalFormats = new Array('y-M-d', 'MMM d, y', 'MMM d,y', 'y-MMM-d', 'd-MMM-y', 'MMM d', 'MMM-d', 'd-MMM');
        var monthFirst = new Array('M/d/y', 'M-d-y', 'M.d.y', 'M/d', 'M-d');
        var dateFirst = new Array('d/M/y', 'd-M-y', 'd.M.y', 'd/M', 'd-M');
        var checkList = new Array(generalFormats, Date.preferAmericanFormat ? monthFirst : dateFirst, Date.preferAmericanFormat ? dateFirst : monthFirst);
        for (var i = 0; i < checkList.length; i++) {
            var l = checkList[i];
            for (var j = 0; j < l.length; j++) {
                var d = Date.parseString(val, l[j]);
                if (d != null) {
                    return d;
                }
            }
        }
        return null;
    }
    ;
    this.isInteger = function(val) {
        for (var i = 0; i < val.length; i++) {
            if ("1234567890".indexOf(val.charAt(i)) == -1) {
                return false;
            }
        }
        return true;
    };
    this.getInt = function(str, i, minlength, maxlength) {
        for (var x = maxlength; x >= minlength; x--) {
            var token = str.substring(i, i + x);
            if (token.length < minlength) {
                return null;
            }
            if (this.isInteger(token)) {
                return token;
            }
        }
        return null;
    };
    val = val + "";
    format = format + "";
    var i_val = 0;
    var i_format = 0;
    var c = "";
    var token = "";
    var token2 = "";
    var x, y;
    var year = new Date().getFullYear();
    var month = 1;
    var date = 1;
    var hh = 0;
    var mm = 0;
    var ss = 0;
    var ampm = "";
    while (i_format < format.length) {
        // Get next token from format string
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        // Extract contents of value based on format token
        if (token == "yyyy" || token == "yy" || token == "y") {
            if (token == "yyyy") {
                x = 4;
                y = 4;
            }
            if (token == "yy") {
                x = 2;
                y = 2;
            }
            if (token == "y") {
                x = 2;
                y = 4;
            }
            year = this.getInt(val, i_val, x, y);
            if (year == null) {
                return null;
            }
            i_val += year.length;
            if (year.length == 2) {
                if (year > 70) {
                    year = 1900 + (year - 0);
                } else {
                    year = 2000 + (year - 0);
                }
            }
        } else if (token == "MMM" || token == "NNN") {
            month = 0;
            var names = (token == "MMM" ? (Date.monthNames.concat(Date.monthAbbreviations)) : Date.monthAbbreviations);
            for (var i = 0; i < names.length; i++) {
                var month_name = names[i];
                if (val.substring(i_val, i_val + month_name.length).toLowerCase() == month_name.toLowerCase()) {
                    month = (i % 12) + 1;
                    i_val += month_name.length;
                    break;
                }
            }
            if ((month < 1) || (month > 12)) {
                return null;
            }
        } else if (token == "EE" || token == "E") {
            var names = (token == "EE" ? Date.dayNames : Date.dayAbbreviations);
            for (var i = 0; i < names.length; i++) {
                var day_name = names[i];
                if (val.substring(i_val, i_val + day_name.length).toLowerCase() == day_name.toLowerCase()) {
                    i_val += day_name.length;
                    break;
                }
            }
        } else if (token == "MM" || token == "M") {
            month = this.getInt(val, i_val, token.length, 2);
            if (month == null || (month < 1) || (month > 12)) {
                return null;
            }
            i_val += month.length;
        } else if (token == "dd" || token == "d") {
            date = this.getInt(val, i_val, token.length, 2);
            if (date == null || (date < 1) || (date > 31)) {
                return null;
            }
            i_val += date.length;
        } else if (token == "hh" || token == "h") {
            hh = this.getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 12)) {
                return null;
            }
            i_val += hh.length;
        } else if (token == "HH" || token == "H") {
            hh = this.getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 23)) {
                return null;
            }
            i_val += hh.length;
        } else if (token == "KK" || token == "K") {
            hh = this.getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 11)) {
                return null;
            }
            i_val += hh.length;
            hh++;
        } else if (token == "kk" || token == "k") {
            hh = this.getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 24)) {
                return null;
            }
            i_val += hh.length;
            hh--;
        } else if (token == "mm" || token == "m") {
            mm = this.getInt(val, i_val, token.length, 2);
            if (mm == null || (mm < 0) || (mm > 59)) {
                return null;
            }
            i_val += mm.length;
        } else if (token == "ss" || token == "s") {
            ss = this.getInt(val, i_val, token.length, 2);
            if (ss == null || (ss < 0) || (ss > 59)) {
                return null;
            }
            i_val += ss.length;
        } else if (token == "a") {
            if (val.substring(i_val, i_val + 2).toLowerCase() == "am") {
                ampm = "AM";
            } else if (val.substring(i_val, i_val + 2).toLowerCase() == "pm") {
                ampm = "PM";
            } else {
                return null;
            }
            i_val += 2;
        } else {
            if (val.substring(i_val, i_val + token.length) != token) {
                return null;
            } else {
                i_val += token.length;
            }
        }
    }
    // If there are any trailing characters left in the value, it doesn't match
    if (i_val != val.length) {
        return null;
    }
    // Is date valid for month?
    if (month == 2) {
        // Check for leap year
        if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { // leap year
            if (date > 29) {
                return null;
            }
        } else {
            if (date > 28) {
                return null;
            }
        }
    }
    if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
        if (date > 30) {
            return null;
        }
    }
    // Correct hours value
    if (hh < 12 && ampm == "PM") {
        hh = hh - 0 + 12;
    } else if (hh > 11 && ampm == "AM") {
        hh -= 12;
    }
    return new Date(year, month - 1, date, hh, mm, ss);
};


function ddlEventListener(e) { App.load('environment', $("ddlaEnvironment").value); };

// Utility function to append a 0 to single-digit numbers
Date.LZ = function (x) { return (x < 0 || x > 9 ? "" : "0") + x };
// Full month names. Change this for local month names
Date.monthNames = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
// Month abbreviations. Change this for local month names
Date.monthAbbreviations = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
// Full day names. Change this for local month names
Date.dayNames = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
// Day abbreviations. Change this for local month names
Date.dayAbbreviations = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
// Used for parsing ambiguous dates like 1/2/2000 - default to preferring 'American' format meaning Jan 2.
// Set to false to prefer 'European' format meaning Feb 1
Date.preferAmericanFormat = true;

// If the getFullYear() method is not defined, create it
if (!Date.prototype.getFullYear) {
    Date.prototype.getFullYear = function () { var yy = this.getYear(); return (yy < 1900 ? yy + 1900 : yy); };
}

Date.prototype.getDayOfYear = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((this - onejan) / 86400000);
};

Date.prototype.format = function(format) //author: meizz
{
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
